package com.chenfan.ccp.executor.wrapper;

import com.chenfan.ccp.executor.TraceContext;
import com.chenfan.ccp.executor.TraceContextHolder;
import com.chenfan.infra.context.TenantContextHolder;
import com.chenfan.infra.context.UserContextHolder;
import com.chenfan.infra.vo.UserVO;
import org.slf4j.MDC;

import java.util.Map;

/**
 * @author wulg
 * @date 2024/4/29
 */
public abstract class AbstractWrapper {

    protected final Map<String, String> mdcContext = MDC.getCopyOfContextMap();

    protected final TraceContext traceContext = TraceContextHolder.getCurrentContext();

    protected final Long tenantId = TenantContextHolder.getTenantId();

    protected final UserVO userVO = UserContextHolder.getUserVo();

    protected final String token = UserContextHolder.getToken();


    protected void copy() {
        if(this.mdcContext != null){
            MDC.setContextMap(this.mdcContext);
        }
        if(this.traceContext != null){
            TraceContextHolder.setContext(traceContext);
        }
        if(tenantId != null) {
            TenantContextHolder.setTenantId(tenantId);
        }
        if(userVO != null) {
            UserContextHolder.setUserVo(userVO);
        }
        if(token != null) {
            UserContextHolder.setToken(token);
        }
    }

    protected  void clear() {
        if(this.mdcContext != null){
            MDC.clear();
        }
        if(this.traceContext != null){
            TraceContextHolder.clear();
        }
        if(tenantId != null) {
            TenantContextHolder.clear();
        }
        if(userVO != null || token != null) {
            UserContextHolder.remove();
        }
    }
}
